from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render

# Create your views here.

# Serializers define the API representation.
from django.utils import timezone
from rest_framework import serializers, viewsets, routers, status
from rest_framework.decorators import api_view
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.utils import json

from app_server.models import AssignClass, Assignment, StudentSelect, UserScore, UserDetail
from accounts.views import check_login


# 自定义分页类
class AssignmentPagination(PageNumberPagination):
    # 每页显示多少个
    page_size = 10
    # 默认每页显示3个，可以通过传入pager1/?page=2&size=4,改变默认每页显示的个数
    page_size_query_param = "size"
    # 最大页数不超过10
    # max_page_size = 10
    # 获取页码数的
    page_query_param = "page"


class AssignmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Assignment
        fields = "__all__"


@api_view(["GET", ])
@check_login
def get_assign_class(request):
    """
    用在首页，获取大分类
    :param request:
    :return: id, class_name-类名, color-颜色, need_score-需要分数, has_credit-已有分数
    """
    ac = AssignClass.objects.all()
    res_list = []
    for a in ac:
        us, _ = UserScore.objects.get_or_create(to_user_detail=UserDetail.objects.get_or_create(to_user=request.user)[0], to_assign_class=a)
        has_credit = us.has_credit
        tmp_dict = a.__dict__
        del tmp_dict["_state"]
        tmp_dict["has_credit"] = has_credit
        res_list.append(tmp_dict)
    return Response(res_list, status.HTTP_200_OK)


@api_view(["GET", ])
@check_login
def get_user_credit(request):
    """
    获取用户任务完成情况（总）
    :param request:
    :return:
    """
    ud = UserDetail.objects.get_or_create(to_user=request.user)[0]
    mud = {"username": ud.to_user.username, "has_credit": ud.has_credit, "require_credit": ud.require_credit}
    return Response(mud, status.HTTP_200_OK)


@api_view(["GET", ])
def recent_assigns(request, a_class=None):
    """
    assign_class 不传，为全部任务的排序
    assgin_class 传，为选择类别任务的排序
    :param request:
    :param a_class: assign_class， 默认为全部
    :param size: 一页数量 (get)
    :param page: 页码 (get)
    :return: 按照传参，返回相应最近任务的分类器。

    """
    if a_class:
        ac = AssignClass.objects.filter(id=a_class)
        assigns = Assignment.objects.filter(belong_class=ac).filter(activity_time__gte=timezone.now())
    else:
        assigns = Assignment.objects.filter(activity_time__gte=timezone.now())
    ap = AssignmentPagination()
    rap = ap.paginate_queryset(queryset=assigns.order_by("-id"), request=request)
    tas = AssignmentSerializer(instance=rap, many=True)
    return Response(tas.data)


@api_view(["GET", ])
@check_login
def get_assign(request, id_):
    """
    获取单个用户任务详情
    :param request:
    :param id_: 任务id
    :return:
    """
    try:
        assign = Assignment.objects.get(id=id_)
    except:
        return Response("The id is not exit.", status.HTTP_400_BAD_REQUEST)
    pics = assign.assignpics_set.all().values_list("pictures")
    STATUS_CODE = {0: '进行中', 1: '已完成', -1: '未完成'}

    sc = StudentSelect.objects.filter(belong_user=request.user, select_lessons=assign)
    if len(sc) > 0:
        status_ = STATUS_CODE[StudentSelect.objects.filter(belong_user=request.user, select_lessons=assign)[0].status]
    else:
        status_ = "未选课"

    res_data = {
        "user": assign.belong_user.username,
        "class": assign.belong_class.class_name,
        "name": assign.name,
        "credit": assign.credit,
        "create_time": assign.create_time,
        "activity_time": assign.activity_time,
        "site": assign.site,
        "require": assign.require,
        "remark": assign.remark,
        "pics": eval(str(list(pics)).replace("(", "").replace(",)", "")),
        'status': status_,
    }

    return Response(res_data, status.HTTP_200_OK)


@api_view(["GET", ])
@check_login
def operate_student_select(request, operate, assign_id=""):
    """

    :param request:
    :param operate: 操作方式 add 或者 del
    :param assign_id: 任务id
    :return: 成功或失败，及原因
    """
    try:
        assign = Assignment.objects.get(id=assign_id)
    except:
        return Response("Params is not allow.", status.HTTP_400_BAD_REQUEST)

    ss = StudentSelect.objects.filter(belong_user=request.user, select_lessons=assign)

    if operate == "add":
        if assign.activity_time < timezone.now():
            return Response("Assign is already over.", status.HTTP_400_BAD_REQUEST)
        if len(ss) > 0:
            return Response("Assign is already selected.", status.HTTP_400_BAD_REQUEST)

        ss_status = StudentSelect.objects.create(belong_user=request.user, select_lessons=assign)

    elif operate == "del":
        if len(ss) <= 0:
            return Response("Assign is not selected.", status.HTTP_400_BAD_REQUEST)
        sss = StudentSelect.objects.filter(belong_user=request.user, select_lessons=assign)

        for s in sss:
            if s.status == -1:
                return Response("Assign is failed. Can't delete.")

        ss_status = sss.delete()


    else:
        return Response("Operate is not exit.", status.HTTP_400_BAD_REQUEST)

    if ss_status:
        return Response("Operate success", status.HTTP_200_OK)
    else:
        return Response("Operate error", status.HTTP_400_BAD_REQUEST)


@api_view(["GET", ])
@check_login
def assigns_selected(request, status_="-2"):
    """
    用户选择的课程
    :param request:
    :param status_: 不传为所有， -1为未完成， 0为进行中， 1为已完成
    :return: 课程列表
    """
    status_ = int(status_)
    if status_ == -2:
        sss = StudentSelect.objects.filter(belong_user=request.user).values_list("select_lessons", "status")
    elif status_ in (-1, 0, 1):
        sss = StudentSelect.objects.filter(belong_user=request.user, status=status_).values_list("select_lessons", "status")
    else:
        return Response("Status error.", status.HTTP_400_BAD_REQUEST)
    fi_sss = list(sss)
    return Response(fi_sss, status.HTTP_200_OK)


@api_view(["GET", ])
@login_required
def test(request):
    return Response("123")
